package com.mdd.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mdd.admin.service.IOrderMealService;
import com.mdd.admin.validate.commons.PageValidate;
import com.mdd.admin.validate.order.*;
import com.mdd.admin.vo.order.OrderMealVo;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.order.MenuMeal;
import com.mdd.common.entity.order.OrderMeal;
import com.mdd.common.mapper.order.MenuMealMapper;
import com.mdd.common.mapper.order.OrderMealMapper;
import com.mdd.common.util.TimeUtils;
import com.mdd.common.vo.MealSaleDataVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 套餐服务层
 *
 * @author shenjian
 * @createTime 2023年02月11日 15:42:00
 */
@Service
public class OrderMealServiceImpl implements IOrderMealService {

    private static final String STR_FORMAT = "00000";

    @Resource
    OrderMealMapper orderMealMapper;

    @Resource
    MenuMealMapper menuMealMapper;

    @Override
    public PageResult<OrderMealVo> list(PageValidate pageValidate, OrderMealSearchValidate searchValidate) {
        Integer pageNo = pageValidate.getPageNo();
        Integer pageSize = pageValidate.getPageSize();

        QueryWrapper<OrderMeal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0);
        queryWrapper.orderByDesc("id");
        queryWrapper.select(OrderMeal.class, info ->
                !"is_delete".equals(info.getColumn()) &&
                        !"delete_time".equals(info.getColumn()) &&
                        !"update_time".equals(info.getColumn()));

        orderMealMapper.setSearch(queryWrapper, searchValidate, new String[]{
                "=:sn:str",
                "like:mealName@meal_name:str"
        });
        Page<OrderMeal> iPage = orderMealMapper.selectPage(new Page<>(pageNo, pageSize), queryWrapper);
        Map<Integer, List<MealSaleDataVo>> saleMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(iPage.getRecords())) {
            List<Integer> mealIds = iPage.getRecords().stream()
                    .map(OrderMeal::getId)
                    .collect(Collectors.toList());
            List<MealSaleDataVo> dataVos = orderMealMapper.queryMealSaleData(mealIds);
            saleMap = dataVos.stream()
                    .collect(Collectors.groupingBy(MealSaleDataVo::getMealId));
        }
        List<OrderMealVo> list = new LinkedList<>();
        for (OrderMeal meal : iPage.getRecords()) {
            OrderMealVo vo = new OrderMealVo();
            BeanUtils.copyProperties(meal, vo);
            if (saleMap.containsKey(meal.getId())) {
                List<MealSaleDataVo> saleDataVos = saleMap.get(meal.getId());
                vo.setSaleNumber(saleDataVos.get(0).getTotal());
            }
            list.add(vo);
        }
        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    @Override
    public OrderMealVo detail(Integer id) {
        final OrderMeal orderMeal = orderMealMapper.selectById(id);
        Assert.notNull(orderMeal, "套餐不存在！");
        OrderMealVo vo = new OrderMealVo();
        BeanUtils.copyProperties(orderMeal, vo);
        return vo;
    }

    @Override
    public void add(OrderMealCreateValidate createValidate) {
        Assert.isNull(this.orderMealMapper.selectOne(new QueryWrapper<OrderMeal>()
                .eq("sn", createValidate.getSn())
                .last("limit 1")), "编号已存在");
        Assert.isNull(this.orderMealMapper.selectOne(new QueryWrapper<OrderMeal>()
                .eq("meal_name", createValidate.getMealName())
                .eq("is_delete", 0)
                .last("limit 1")), "套餐名称已存在");
        OrderMeal orderMeal = new OrderMeal();
        BeanUtils.copyProperties(createValidate, orderMeal);
        orderMeal.setIsDelete(0);
        orderMeal.setCreateTime(TimeUtils.timestamp());
        this.orderMealMapper.insert(orderMeal);
    }

    @Override
    public void edit(OrderMealUpdateValidate updateValidate) {
        OrderMeal orderMeal = this.orderMealMapper.selectOne(new QueryWrapper<OrderMeal>()
                .eq("id", updateValidate.getId())
                .eq("is_delete", 0)
                .last("limit 1"));
        Assert.notNull(orderMeal, "数据错误，该套餐数据不存在！");
        BeanUtils.copyProperties(updateValidate, orderMeal);
        orderMeal.setUpdateTime(TimeUtils.timestamp());
        this.orderMealMapper.updateById(orderMeal);
    }

    @Override
    public void del(Integer id) {
        OrderMeal orderMeal = this.orderMealMapper.selectOne(new QueryWrapper<OrderMeal>()
                .eq("id", id)
                .eq("is_delete", 0)
                .last("limit 1"));
        Assert.notNull(orderMeal, "数据错误，该套餐数据不存在！");
        orderMeal.setIsDelete(1);
        orderMeal.setDeleteTime(TimeUtils.timestamp());
        this.orderMealMapper.updateById(orderMeal);
        // 套餐删除后，未生效的套餐删除
        this.menuMealMapper.delete(new QueryWrapper<MenuMeal>()
                .eq("meal_id", id)
                .eq("menu_status", 0));
    }

    @Override
    public String createSn() {
        Long count = this.orderMealMapper.selectCount(new QueryWrapper<>());
        count++;
        DecimalFormat df = new DecimalFormat(STR_FORMAT);
        return df.format(count);
    }
}
